
const express = require('express'); // 导入 Express 模块
const fs = require('node:fs'); // node内置模块，用于文件系统操作。
const path = require('node:path');//node内置模块，用于处理文件路径。
const axios = require('axios'); // 导入 Axios 模块，用于发起 HTTP 请求
const app = express(); // 创建 Express 应用实例
const WxPay = require('wechatpay-node-v3'); // 导入微信支付模块
const bodyParser = require('body-parser');  // 中间件，用于解析req.body
const crypto = require('crypto'); // 加密模块

const pay = express.Router();
const connection = require("../config");

app.use(bodyParser.json());  // 使用中间件解析JSON数据

const wxConfig = {
    appid: '',
    secret: '',
    mchid: '1660333514', //商戶號
    serial_no: '', //API證書-商戶API證書序列號
    publicKey: fs.readFileSync(`${__dirname}/certificate/apiclient_cert.pem`)
    .toString(), //公鈅
    privateKey: fs.readFileSync(`${__dirname}/certificate/apiclient_key.pem`)
    .toString(), //秘鈅
    apiV3Key: 'your_apiV3Key', //apiV3 秘钥值
    mchKey: 'your_mch_key', // 微信支付商户密钥
}

const wechatPay = new WxPay({
    appid: wxConfig.appid,
    mchid: wxConfig.mchid,
    publicKey: wxConfig.publicKey,
    privateKey: wxConfig.privateKey
});


pay.post('/weChatMp/login', async (req, res) => {
    console.log(req)
    const code = req.body?.code;
    
    if (!code) {
        throw new Error('code參數不能為空')
    }

    const url = `https://api.weixin.qq.com/sns/jscode2session`;

    const response = await axios({
        method: "GET",
        url,
        params: {
            appid: wxConfig.appid,
            secret: wxConfig.secret,
            js_code: code,
            grant_type: 'authorization_code'
        }
    })

    if (response?.errCode) {
        throw new Error(JSON.stringify(response))
    }

    res.send({
        msg: '獲取openid成功',
        data: {
            openId: response.data.openid
        }
    })
})

module.exports = pay;